var ZYRequestClient = require("../../../../utils/zy-request");
var requestClient;
const app = getApp();
Page({
  data: {
    userId:0,
    tabbarContentHeight:600,
    titles:['新申请','我提交的','我审批的','抄送我的'],
    approvalStatusTexts:['待审批','审批中','已通过','已驳回','已撤销','已关闭'],
    approvalStatusClass:['pending-approval','in-approval','pass','reject','revoke','pass'],
    showAgreeDialog:false,
    agreeComment:'同意',
    agreeApplyId:0,
    showRejectDialog:false,
    rejectComment:'',
    rejectApplyId:0,
    showUserDialog:false,
    checkUserId:0,
    replaceApplyId:0,
    blockId:0,
    showPublish:false,
    submitLoading:false,
    formData: {},
    expireDate:'',
    startDate:'',
    endDate:'',
    files: [],
    imageUrls:[],
    rules: [
      {
          name: 'reason',
          rules: [{required: true, message: '请输入用印事由'},{maxlength:200,message:'用印事由最长200个字'}],
      }, 
      {
          name: 'fileName',
          rules: [{required: true, message: '请输入文件名称'},{maxlength:50,message:'文件名称最长50个字'}],
      }, 
      {
        name: 'fileNumber',
        rules: [{required: true, message: '请输入文件份数'},{min:1,message:'文件份数最小为1'}],
      }, 
      {
          name: 'applyCount',
          rules: [{required: true, message: '请输入盖章次数'},{min:1,message:'盖章次数最小为1'},{max:10000,message:'盖章次数最大为10000次'}],
      }
    ],
    tabbarlist: [
        {
            text: '新申请',
            iconPath: "/pages/images/workbench/tb_apply.png",
            selectedIconPath: "/pages/images/workbench/tb_apply_slt.png",
        },
        {
            text: '我提交的',
            iconPath: "/pages/images/workbench/tb_submit.png",
            selectedIconPath: "/pages/images/workbench/tb_submit_slt.png"
        },
        {
            text: '我审批的',
            iconPath: "/pages/images/workbench/tb_approval.png",
            selectedIconPath: "/pages/images/workbench/tb_approval_slt.png",
            dot: false
        },
        {
            text: '抄送我的',
            iconPath: "/pages/images/workbench/tb_cc.png",
            selectedIconPath: "/pages/images/workbench/tb_cc_slt.png",
            //badge: '3'
        }
    ],
    sealList:[],
    selectedSeal:null,
    approvalProcessList:[],
    approvalProcessId:0,
    selectedApproval:null,
    approvalProcessUserList:[],
    
    fileTypeIndex:[0,0],
    // 申请单文件类型选项
    fileTypeArray:[],
    fileTypeParentArray:[],
    fileTypeChildArray:[],

    dateTimeArray: null,
    dateTime: null,
    startYear: 2021,
    endYear: 2050,

    facePhoto:true,
    switchFaceDisabled:false,

    switchDisabled:false,
    stampPhotograph:false,

    showFacePhoto:true,
    showStampPhotograph:true,

    // 我提交的申请单查询条件
    myStatusIndex:0,
    myFileTypeIndex:[0,0],
    mySubmitDateIndex:0,

    // 我审批的申请单据查询条件
    myApprovalSelectedUser:null,
    myApprovalFileTypeIndex:[0,0],
    myApprovalUserIndex:0,
    myApprovalSubmitDateIndex:0,
    handleStatusNumber:0,// 处理状态
    
    // 抄送我的申请单据查询条件
    myCCSelectedUser:null,
    myCCApprovalStatusIndex:0,
    myCCFileTypeIndex:[0,0],
    myCCUserIndex:0,
    myCCSubmitDateIndex:0,

    // 审批状态选项
    approvalStatusList:[
      {text:'全部',value:null},
      {text:'待审批',value:0},
      {text:'审批中',value:1},
      {text:'通过',value:2},
      {text:'驳回',value:3},
      {text:'撤销',value:4},
      {text:'已关闭',value:5}
    ],
    // 文件类型
    applyFileTypeList:[],
    // 提交日期选项
    submitDateList:[
      {text:'全部',value:null},
      {text:'近7日',value:7},
      {text:'近半个月',value:15},
      {text:'近一个月',value:30}
    ],
    // 申请人选项
    applyUserList:[],
    // 转交人选项
    transferUserList:[],

    // 我提交的申请单
    applyOfMyList:[],
    myApplyParams:{
      userId:null,
      approvalStatus:null,
      fileType:null,
      applyUserId:null,
      duration:null,
      handlerStatus:null,
      keyWords:null,
      pageNo:0,
    },
    // 我审批的申请单
    applyOfMyApprovalList:[],
    myApprovalParams:{
      userId:null,
      approvalStatus:null,
      fileType:null,
      applyUserId:null,
      duration:null,
      handlerStatus:null,
      keyWords:null,
      pageNo:0,
    },
    // 抄送我的申请单
    applyOfMyCCList:[],
    myCCParams:{
      userId:null,
      approvalStatus:null,
      fileType:null,
      applyUserId:null,
      duration:null,
      handlerStatus:null,
      keyWords:null,
      pageNo:0,
    },
    navbarData:{
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '新申请', //导航栏 中间的标题
      white:true
     },
     // 导航头的高度
     height: app.globalData.height * 2 + 20,
     sizeType:['compressed'],
     maxCount:100,
     maxSize:10*1024*1024
  },
  onLoad(options) {
    requestClient = new ZYRequestClient();
    // 设置内容高度
    this.setTabbarContentHeight();
    // 获取当前用户
    var userInfo = wx.getStorageSync('userInfo');
    if(userInfo == ''){
      userInfo = {id:0};
    }
    this.setData({
      selectFile: this.selectFile.bind(this),
      uploadImage: this.uploadImage.bind(this),
      userId:userInfo.id
    });
    // 设置选中的页签
    var e = {detail:{
      index:0
    }}
    if(options.blockId){
      e = {detail:{
        index:parseInt(options.blockId)
      }}
    }
    this.tabChange(e);
    // 加载数据
    this.getAllUserList();
    this.getHasMyApproval();
    this.initData();
  },
  onShow(){
    var _this = this;
    if(_this.data.blockId == 0){
      var useSealData = wx.getStorageSync('useSealData');
      if(useSealData){
        wx.showModal({
          title:'提示',
          content:'您最近有提交用印申请，是否复制上次填写的信息？',
          success(r){
            if(r.confirm){
              _this.setData({
                'formData.reason':useSealData.reason,
                'formData.fileName':useSealData.fileName,
                'formData.fileNumber':useSealData.fileNumber,
                'formData.applyCount':useSealData.applyCount,
              });
            }
          }
        })
      }
    }
    // 获取合同类型
    this.getContractTypeList();
  },
  initData(){
    var dateTime = new Date();
    dateTime=dateTime.setDate(dateTime.getDate()+1);
    var now = dateTime=new Date(dateTime);
    var year = now.getFullYear();
    var month = now.getMonth();
    month = month +1;
    month = month <10 ? ('0' + month):month;
    var day = now.getDate();
    day = day <10 ? ('0' + day):day;
    var expireDate = year + '-' + month + '-' + day;
    this.setData({
      expireDate:expireDate,
      startDate:expireDate
    });
    var endYear = now.getFullYear() + 1;
    var endMonth = now.getMonth();
    endMonth = endMonth +1;
    endMonth = endMonth <10 ? ('0' + endMonth):endMonth;
    var endDay = now.getDate();
    endDay = endDay <10 ? ('0' + endDay):endDay;
    var endDate = endYear + '-' + endMonth + '-' + endDay;
    this.setData({
      endDate:endDate
    });
    this.setData({
      myApplySearch: this.myApplySearch.bind(this),
      myApprovalSearch: this.myApprovalSearch.bind(this),
      myCCSearch: this.myCCSearch.bind(this)
    })
    // 获取印章列表
    this.loadSealList();
  },
  // 设置Tabbar内容高度
  setTabbarContentHeight:function(){
    var _this = this;
    wx.createSelectorQuery()
    .select("#tabbar")
    .boundingClientRect(function(rect){
        // 获取系统信息得到屏幕高度
        wx.getSystemInfo({
          success: function (res) {
            let clientHeight = res.windowHeight;
              _this.setData({
                tabbarContentHeight:clientHeight - rect.height
              });
          }
        });
    }).exec();
  },
  // 获取印章列表
  loadSealList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(defaultCompany == ''){
      defaultCompany = { id: 0 };
    }
    requestClient.getSealList(defaultCompany.id,function(res){
      _this.setData({
        sealList:res.data.data
      });
    });
  },
  // 获取印章审批流列表
  loadSealApprovalProcessList(sealId){
    var _this = this;
    requestClient.getApprovalProcessListBySealId(sealId,function(res){
      _this.setData({
        approvalProcessList:res.data.data
      });
    })
  },
  // 获取审批流详情
  getApprovalProcessDetail(id){
    var _this = this;
    requestClient.getApprovalProcessDetail(id,function(res){
      if(res.data.data){
        if(res.data.data.approvalProcess.enableFlag){
          var approvalProcessUserList = [];
          // 审批人
          if(res.data.data.approvalUserList.length > 0){
              var approvalUserList = res.data.data.approvalUserList;
              for(var i= 0;i < approvalUserList.length; i++){
                  var approvalUser = approvalUserList[i];
                  var userVoList = approvalUser.userVoList;
                  var userList = [];
                  for(var j = 0; j< userVoList.length; j ++){
                      var user = userVoList[j];
                      var aUser = {
                        userHeadPortrait:user.avatarUrl,
                        userName:user.nickName
                      };
                      userList.push(aUser);
                  }
                  var approvalUser = {
                    approvalType:'approval',
                    display:0,
                    title:'审批人',
                    userList:userList
                };
                approvalProcessUserList.push(approvalUser);
              }
              _this.setData({
                approvalProcessId:res.data.data.approvalProcess.id
              });
          } else {
            _this.setData({
              approvalProcessId:0
            });
            wx.showToast({
              title: '当前审批流没有审批人',
              icon:'none'
            })
          }
          // 抄送人
          if(res.data.data.ccUser){
              var ccUser = res.data.data.ccUser;
              var userVoList = ccUser.userVoList;
              if(userVoList){
                var ccUserList = [];
                for(var i = 0; i< userVoList.length; i ++){
                    var user = userVoList[i];
                    var ccUser = {
                      userHeadPortrait:user.avatarUrl,
                      userName:user.nickName
                    };
                    ccUserList.push(ccUser);
                }
                var approvalCCUser = {
                    approvalType:'user',
                    display:0,
                    title:'抄送人',
                    userList:ccUserList
                };
                approvalProcessUserList.push(approvalCCUser);
              }
          }
          _this.setData({
            approvalProcessUserList:approvalProcessUserList
          });
        } else {
          _this.setData({
            approvalProcessId:0,
            approvalProcessUserList:[]
          });
          wx.showModal({
            title:'用印申请',
            content:'此印章审批流已经禁用，请联系管理员！',
            showCancel:false,
            success(r){
              
            }
          })
        }
      }
    })
  },
  // 获取合同类型
  getContractTypeList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(defaultCompany == ''){
      defaultCompany = { id:0 };
    }
    requestClient.getCompanyContractList(defaultCompany.id,function(res){
      res.data.data.parentList.splice(0,0,"全部");
      res.data.data.childList.splice(0,0,["请选择文件类型"]);
      _this.setData({
        fileTypeParentArray:res.data.data.parentList,
        fileTypeChildArray:res.data.data.childList
      });
      _this.setData({
        fileTypeArray:[_this.data.fileTypeParentArray,_this.data.fileTypeChildArray[0]]
      });
      _this.setData({
        applyFileTypeList:[_this.data.fileTypeParentArray,_this.data.fileTypeChildArray[0]]
      });
    })
  },
  // 获取公司下所有用户(排除本人)
  getAllUserList(){
    var _this = this;
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(defaultCompany == ''){
      defaultCompany = {id:0};
    }
    requestClient.getAllUserList(defaultCompany.id,function(res){
      var newUserList = [];
      var defaultUser = {id:null,nickName:'全部'};
      newUserList.push(defaultUser);
      var transferUserList = [];
      // 排除本人
      for(var i=0;i< res.data.data.length;i++){
        var user = res.data.data[i];
        if(user.id == _this.data.userId){
          continue;
        }
        var newUser = {id:user.id,nickName:user.nickName};
        newUserList.push(newUser);

        var transferUser = {id:user.id,nickName:user.nickName};
        transferUserList.push(transferUser);
      }
      _this.setData({
        applyUserList:newUserList,
        transferUserList:transferUserList
      });
    })
  },
  // 显示申请选择印章对话框
  bindShowSelectSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:true,
    });
  },
  // 确认选择印章
  bindSealCheck(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
    var sealList = _this.data.sealList;
    for(var i=0;i<sealList.length;i++){
      if(sealList[i].id == parseInt(e.detail.value)){
        _this.setData({
          selectedSeal:sealList[i]
        });
        break;
      }
    }
    _this.setData({
      approvalProcessId:0,
      approvalProcessUserList:[],
      approvalProcessList:[],
    });
    var seal = _this.data.selectedSeal;
    _this.setData({
      showFacePhoto:!seal.facePhoto,
      facePhoto:seal.facePhoto,
      switchFaceDisabled:seal.facePhoto,
      showStampPhotograph:!seal.forcePhotograph,
      switchDisabled:seal.forcePhotograph,
      stampPhotograph:seal.forcePhotograph
    });
    _this.loadSealApprovalProcessList(seal.id);
  },
  // 关闭选择印章
  bindClosedSeal(e){
    var _this = this;
    _this.setData({
      showSealDialog:false,
    });
  },
  // 显示申请选择审批流程对话框
  bindShowSelectApproval(e){
    var _this = this;
    _this.setData({
      showApprovalDialog:true,
    });
  },
  // 确认选择审批流程
  bindApprovalCheck(e){
    var _this = this;
    _this.setData({
      showApprovalDialog:false,
    });
    var approvalProcessList = _this.data.approvalProcessList;
    for(var i=0;i<approvalProcessList.length;i++){
      if(approvalProcessList[i].id == parseInt(e.detail.value)){
        _this.setData({
          selectedApproval:approvalProcessList[i],
          approvalProcessId:approvalProcessList[i].id,
        });
        // 获取审批详情
        _this.getApprovalProcessDetail(approvalProcessList[i].id);
        break;
      }
    }
  },
  // 关闭选择审批流程
  bindClosedApproval(e){
    var _this = this;
    _this.setData({
      showApprovalDialog:false,
    });
  },
  // 获取是否有待我审批的申请单
  getHasMyApproval(){
    var _this = this;
    requestClient.getHasMyApproval(_this.data.userId,function(res){
        var tabbarList = _this.data.tabbarlist;
        tabbarList[2].dot = res.data.data;
        _this.setData({
          tabbarlist:tabbarList
        });
    })
  },
  // 加载我提交的申请单
  loadMyApplyList(append){
    var _this = this;
    if(append){
      wx.showLoading({
        title: '加载更多',
        mask:true
      })
    } else {
      wx.showLoading({
        title: '刷新数据',
        mask:true
      })
    }
    requestClient.getMyApplyList(_this.data.myApplyParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      if(res.data.data){
        if(append){
          var applyOfMyList = _this.data.applyOfMyList.concat(res.data.data);
          _this.setData({
            applyOfMyList:applyOfMyList
          });
        } else {
          _this.setData({
            applyOfMyList:res.data.data
          });
        }
      }
    })
  },
  // 加载我审批的申请单
  loadMyApprovalList(append){
    var _this = this;
    if(append){
      wx.showLoading({
        title: '加载更多',
        mask:true
      })
    } else {
      wx.showLoading({
        title: '刷新数据',
        mask:true
      })
    }
    requestClient.getMyApprovalApplyList(_this.data.myApprovalParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      if(res.data.data){
        if(append){
          var applyOfMyApprovalList = _this.data.applyOfMyApprovalList.concat(res.data.data);
          _this.setData({
            applyOfMyApprovalList:applyOfMyApprovalList
          });
        } else {
          _this.setData({
            applyOfMyApprovalList:res.data.data
          });
        }
      }
      _this.getHasMyApproval();
    })
  },
  // 加载抄送我的申请单
  loadMyCCList(append){
    var _this = this;
    if(append){
      wx.showLoading({
        title: '加载更多',
        mask:true
      })
    } else {
      wx.showLoading({
        title: '刷新数据',
        mask:true
      })
    }
    requestClient.getMyCCApplyList(_this.data.myCCParams,function(res){
      wx.hideLoading({
        success: (res) => {},
      })
      if(res.data.data){
        if(append){
          var applyOfMyCCList = _this.data.applyOfMyCCList.concat(res.data.data);
          _this.setData({
            applyOfMyCCList:applyOfMyCCList
          });
        } else {
          _this.setData({
            applyOfMyCCList:res.data.data
          });
        }
      }
    })
  },
  // 文本框输入
  formInputChange(e) {
    var _this = this;
    // 判断是否选择印章
    var seal = _this.data.selectedSeal;
    if(seal == null){
      wx.showModal({
        title:'请选择印章',
        content:'请您选择需要申请的印章名称',
        showCancel:false,
        success(r){

        }
      })
      const {field} = e.currentTarget.dataset;
      this.setData({
          [`formData.${field}`]: ''
      })
    } else {
      const {field} = e.currentTarget.dataset;
      this.setData({
          [`formData.${field}`]: e.detail.value
      })
    }
    
  },
  // 选择文件（可能有多张图片）
  selectFile(files) {
    let _this = this;
    for(let i = 0;i<files.tempFiles.length;i++){
      // 判断文件后缀名和大小
      var selectFile = files.tempFiles[i];
      var etds= selectFile.path.split('.');
      if(etds.length ==2){
          var etd = etds[1].toLowerCase();
        if(etd!="jpg" && etd !="png" && etd!="jpeg"){
            wx.showToast({
                title: '请上传JPG或PNG！',
              })
              return false;
        } else {
            var size = selectFile.size;
            if(size > _this.data.maxSize){
                wx.showToast({
                    title: '请上传小于10兆的图片!',
                  })
                  return false;
            }
        }
      } else {
        wx.showToast({
          title: '文件上传有误！',
        })
        return false;
      }
    }
    
    return true;
  },
  // 上传图片
  uploadImage(files) {
    let that = this;
    let tempFilePaths = files.tempFilePaths;
    // 文件上传的函数，返回一个promise
    return new Promise((resolve, reject) => {
      var urls = [];
      tempFilePaths.map((tempFilePath)=>{
        that.uploadFile(tempFilePath).then(imgUrl => {
          if(imgUrl){
            let imageUrls = that.data.imageUrls;
            imageUrls.push(imgUrl);
            that.setData({
              imageUrls:imageUrls
            });
            urls.push(imgUrl);
            // 判断是否上传完毕
            if(urls.length == tempFilePaths.length){
              resolve({urls:urls});
            }
          } else {
            reject('上传失败！');
          }
        });
      });
    });
  },
  uploadFile(tempFilePath){
    let that = this;
    return new Promise(resolve => {
      requestClient.uploadImage(that.data.userId,tempFilePath,function(res){
        resolve(res.data)
      });
    });
  },
  // 上传失败
  uploadError(e) {
      wx.showToast({
        title: '上传失败！',
      })
  },
  // 删除上传的图片
  deleteImage(e){
    var _this = this;
    var imageUrls = _this.data.imageUrls;
    imageUrls.splice(e.detail.index,1);
    _this.setData({
      imageUrls:imageUrls
    });
  },
  // 选择文件类型
  changeFileType(e){
    var _this = this;
    _this.setData({
      fileTypeIndex:e.detail.value
    });
  },
  changeFileTypeColumn(e){
    var _this = this;
    // 如果是第一列则更新第二列的选项
    if(e.detail.column == 0){
      var fileTypeArray = _this.data.fileTypeArray;
      fileTypeArray[1] = _this.data.fileTypeChildArray[e.detail.value];
      _this.setData({
        fileTypeArray:fileTypeArray
      });
    }
    var fileTypeIndex = _this.data.fileTypeIndex;
    fileTypeIndex[e.detail.column] = e.detail.value;
    _this.setData({
      fileTypeIndex:fileTypeIndex
    });
  },
  // 跳转添加文件类型
  bindAddoCntractType(e){
    wx.navigateTo({
      url: '../contracttype/index',
    })
  },
  // 选择用印时间
  changeExpireDate(e){
    this.setData({
      expireDate:e.detail.value
    });
  },
  // 盖章前确认用印人开关
  bindSwitchFaceChange(e){
    var _this = this;
    _this.setData({
      facePhoto:e.detail.value
    });
  },
  // 盖章时自动拍照开关
  bindSwitchChange(e){
    var _this = this;
    _this.setData({
      stampPhotograph:e.detail.value
    });
  },
  //提交申请
  submitForm(){
    var _this = this;
    if(_this.data.submitLoading){
      return;
    }
    this.selectComponent('#form').validate((valid, errors) => {
        if (!valid) {
            const firstError = Object.keys(errors)
            if (firstError.length) {
              // 提示用户
              wx.showToast({
                title: errors[firstError[0]].message,
                icon:'none'
              })
            }
        } else {
          if(_this.checkSubmitData()){
              _this.setData({
                submitLoading:true
              });
              // 构造申请数据
              var expireTime = _this.data.expireDate + ' 23:59:59';
              var applyData = {
                sealId:_this.data.selectedSeal.id,
                sealName:_this.data.selectedSeal.name,
                companyId:_this.data.selectedSeal.companyId,
                reason:_this.data.formData.reason,
                fileName:_this.data.formData.fileName,
                fileType:_this.data.fileTypeArray[1][_this.data.fileTypeIndex[1]],
                fileNumber:_this.data.formData.fileNumber,
                applyCount:_this.data.formData.applyCount,
                expireTime:expireTime,
                stampPhotograph:_this.data.stampPhotograph,
                facePhoto:_this.data.facePhoto,
                createUser:_this.data.userId,
                approvalProcessId:_this.data.approvalProcessId,
                imageUrls:_this.data.imageUrls
              };
              wx.setStorageSync('useSealData', applyData);
              wx.redirectTo({
                url: '../applyphoto/index',
              })
          }
        }
    })
  },
  // 校验参数
  checkSubmitData(){
    var _this = this;
    // 判断选择印章
    var seal = _this.data.selectedSeal;
    if(seal == null){
      // 提示用户
      wx.showToast({
        title: '请选择申请印章',
        icon:'none'
      })
      return false;
    } else {
      // 判断印章是否过期
      if(seal.expireStatus){
        wx.showModal({
          title:'申请失败',
          content:'服务费已过期，您是否去充值？',
          confirmText:'去充值',
          cancelText:'先不用',
          success(r){
            if(r.confirm){
              wx.navigateTo({
                url: '../recharge/index',
              })
            }
          }
        });
        return false;
      }
      if(seal.status == 0){
        // 提示用户
        wx.showToast({
          title: '此印章已经删除',
          icon:'none'
        })
        return false;
      }
      if(seal.status == 1){
        // 提示用户
        wx.showToast({
          title: '此印章已停用',
          icon:'none'
        })
        return false;
      }
    }
    // 判断选择审批流
    if(_this.data.approvalProcessId == 0){
      // 提示用户
      wx.showToast({
        title: '请选择审批流程',
        icon:'none'
      })
      return false;
    }
    // 判断选择文件类型
    if(_this.data.fileTypeIndex[0] == 0 && _this.data.fileTypeIndex[1] == 0){
      // 提示用户
      wx.showToast({
        title: '请选择文件类型',
        icon:'none'
      })
      return false;
    }
    // 判断文件份数是否为数字
    var regNum=new RegExp('[0-9]','g');
    if(regNum.exec(_this.data.formData.fileNumber) == null){
      // 提示用户
      wx.showToast({
        title: '文件份数只能为数字',
        icon:'none'
      })
      return false;
    }
    // 判断盖章次数是否为数字
    regNum=new RegExp('[0-9]','g');
    if(regNum.exec(_this.data.formData.applyCount) == null){
       // 提示用户
       wx.showToast({
        title: '盖章次数只能为数字',
        icon:'none'
      })
      return false;
    }
    // 判断是否拍照上传
    // if(_this.data.imageUrls.length == 0){
    //   // 提示用户
    //   wx.showToast({
    //     title: '请拍照上传文件',
    //     icon:'none'
    //   })
    //   return false;
    // }

    return true;
  },

  // 我提交的申请单查询
  myApplySearch:function(value){
    if(value==''){
      this.setData({
        'myApplyParams.keyWords':null
      });
    } else {
      this.setData({
        'myApplyParams.keyWords':value
      });
    }
    this.loadMyApplyList(false);

    return new Promise((resolve, reject) => {
      setTimeout(() => {
          resolve([])
      }, 200)
    })
  },
  applySearchClear(e){
    this.setData({
      'myApplyParams.keyWords':null
    });
    this.loadMyApplyList(false);
  },
  bindMyStatusChange(e){
    this.setData({
      myStatusIndex:e.detail.value,
      'myApplyParams.approvalStatus':this.data.approvalStatusList[e.detail.value].value
    });
    this.loadMyApplyList(false);
  },
  changeMyFileType(e){
    this.setData({
      myFileTypeIndex:e.detail.value
    });
    if(e.detail.value[0] == 0){
      this.setData({
        'myApplyParams.fileType':null
      });
    } else {
      this.setData({
        'myApplyParams.fileType':this.data.applyFileTypeList[1][e.detail.value[1]]
      });
    }
    this.loadMyApplyList(false);
  },
  changeMyFileTypeColumn(e){
    var _this = this;
    // 如果是第一列则更新第二列的选项
    if(e.detail.column == 0){
      var applyFileTypeList = _this.data.applyFileTypeList;
      applyFileTypeList[1] = _this.data.fileTypeChildArray[e.detail.value];
      _this.setData({
        applyFileTypeList:applyFileTypeList
      });
    }
    var myFileTypeIndex = _this.data.myFileTypeIndex;
    myFileTypeIndex[e.detail.column] = e.detail.value;
    _this.setData({
      myFileTypeIndex:myFileTypeIndex
    });
  },
  bindMySubmitDateChange(e){
    this.setData({
      mySubmitDateIndex:e.detail.value,
      'myApplyParams.duration':this.data.submitDateList[e.detail.value].value
    });
    this.loadMyApplyList(false);
  },

  // 我审批的申请单查询
  myApprovalSearch:function(value){
    if(value==''){
      this.setData({
        'myApprovalParams.keyWords':null
      });
    } else {
      this.setData({
        'myApprovalParams.keyWords':value
      });
    }
    this.loadMyApprovalList(false);
    
    return new Promise((resolve, reject) => {
      setTimeout(() => {
          resolve([])
      }, 200)
    })
  },
  approvalSearchClear(e){
    this.setData({
      'myApprovalParams.keyWords':null
    });
    this.loadMyApprovalList(false);
  },
  bindHandleStatus(e){
    this.setData({
      handleStatusNumber: parseInt(e.currentTarget.dataset.num),
      'myApprovalParams.handlerStatus':parseInt(e.currentTarget.dataset.num)
    });
    this.loadMyApprovalList(false);
  },
  changeMyApprovalFileType(e){
    this.setData({
      myApprovalFileTypeIndex:e.detail.value
    });
    if(e.detail.value[0] == 0){
      this.setData({
        'myApprovalParams.fileType':null
      });
    } else {
      this.setData({
        'myApprovalParams.fileType':this.data.applyFileTypeList[1][e.detail.value[1]]
      });
    }
    this.loadMyApprovalList(false);
  },
  changeMyApprovalFileTypeColumn(e){
    var _this = this;
    // 如果是第一列则更新第二列的选项
    if(e.detail.column == 0){
      var applyFileTypeList = _this.data.applyFileTypeList;
      applyFileTypeList[1] = _this.data.fileTypeChildArray[e.detail.value];
      _this.setData({
        applyFileTypeList:applyFileTypeList
      });
    }
    var myApprovalFileTypeIndex = _this.data.myApprovalFileTypeIndex;
    myApprovalFileTypeIndex[e.detail.column] = e.detail.value;
    _this.setData({
      myApprovalFileTypeIndex:myApprovalFileTypeIndex
    });
  },
  bindMyApprovalUserChange(e){
    this.setData({
      myApprovalUserIndex:parseInt(e.detail.value),
      'myApprovalParams.applyUserId':this.data.applyUserList[parseInt(e.detail.value)].id
    });
    this.loadMyApprovalList(false);
  },
  bindMyApprovalSubmitDateChange(e){
    this.setData({
      myApprovalSubmitDateIndex:e.detail.value,
      'myApprovalParams.duration':this.data.submitDateList[e.detail.value].value
    });
    this.loadMyApprovalList(false);
  },
  bindSelectMyApprovalUser(e){
    var _this = this;
    _this.setData({
      showMyApprovalUserDialog:true,
    });
  },
  bindMyApprovalUserCheck(e){
    var _this = this;
    _this.setData({
      showMyApprovalUserDialog:false,
    });
    var id = e.detail.value;
    if(!!id){
      for(var i=0;i<_this.data.applyUserList.length;i++){
        var applyUser = _this.data.applyUserList[i];
        if(applyUser.id == parseInt(id)){
          _this.setData({
            myApprovalSelectedUser:applyUser,
          });
          break;
        }
      }
    } else {
      _this.setData({
        myApprovalSelectedUser:null,
      });
    }
    _this.setData({
      'myApprovalParams.applyUserId':id,
    });
    _this.loadMyApprovalList(false);
  },
  bindMyApprovalClosedUser(e){
    var _this = this;
    _this.setData({
      showMyApprovalUserDialog:false,
    });
  },
  // 抄送我的申请单查询
  myCCSearch:function(value){
    if(value==''){
      this.setData({
        'myCCParams.keyWords':null
      });
    } else {
      this.setData({
        'myCCParams.keyWords':value
      });
    }
    this.loadMyCCList(false);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
          resolve([])
      }, 200)
    })
  },
  ccSearchClear(e){
    this.setData({
      'myCCParams.keyWords':null
    });
    this.loadMyCCList(false);
  },
  bindMyCCApprovalStatusChange(e){
    this.setData({
      myCCApprovalStatusIndex:e.detail.value,
      'myCCParams.approvalStatus':this.data.approvalStatusList[e.detail.value].value
    });
    this.loadMyCCList(false);
  },
  changeMyCCFileType(e){
    this.setData({
      myCCFileTypeIndex:e.detail.value
    });
    if(e.detail.value[0] == 0){
      this.setData({
        'myCCParams.fileType':null
      });
    } else {
      this.setData({
        'myCCParams.fileType':this.data.applyFileTypeList[1][e.detail.value[1]]
      });
    }
    this.loadMyCCList(false);
  },
  changeMyCCFileTypeColumn(e){
    var _this = this;
    // 如果是第一列则更新第二列的选项
    if(e.detail.column == 0){
      var applyFileTypeList = _this.data.applyFileTypeList;
      applyFileTypeList[1] = _this.data.fileTypeChildArray[e.detail.value];
      _this.setData({
        applyFileTypeList:applyFileTypeList
      });
    }
    var myCCFileTypeIndex = _this.data.myCCFileTypeIndex;
    myCCFileTypeIndex[e.detail.column] = e.detail.value;
    _this.setData({
      myCCFileTypeIndex:myCCFileTypeIndex
    });
  },
  bindMyCCUserChange(e){
    this.setData({
      myCCUserIndex:parseInt(e.detail.value),
      'myCCParams.applyUserId':this.data.applyUserList[parseInt(e.detail.value)].id
    });
    this.loadMyCCList(false);
  },
  bindMyCCSubmitDateChange(e){
    this.setData({
      myCCSubmitDateIndex:e.detail.value,
      'myCCParams.duration':this.data.submitDateList[e.detail.value].value
    });
    this.loadMyCCList(false);
  },

  bindSelectMyCCUser(e){
    var _this = this;
    _this.setData({
      showMyCCUserDialog:true,
    });
  },
  bindMyCCUserCheck(e){
    var _this = this;
    _this.setData({
      showMyCCUserDialog:false,
    });
    var id = e.detail.value;
    if(!!id){
      for(var i=0;i<_this.data.applyUserList.length;i++){
        var applyUser = _this.data.applyUserList[i];
        if(applyUser.id == parseInt(id)){
          _this.setData({
            myCCSelectedUser:applyUser,
          });
          break;
        }
      }
    } else {
      _this.setData({
        myCCSelectedUser:null,
      });
    }
    _this.setData({
      'myCCParams.applyUserId':id,
    });
    _this.loadMyCCList(false);
  },
  bindMyCCClosedUser(e){
    var _this = this;
    _this.setData({
      showMyCCUserDialog:false,
    });
  },
  // 我提交的申请单上拉刷新
  refreshMyApplyList(e){
    var _this = this;
    _this.setData({
      'myApplyParams.pageNo':0
    });
    _this.loadMyApplyList(false);
  },
  // 我提交的申请单下拉加载更多数据
  loadMoreMyApplyList(e){
    var _this = this;
    var pageNo = _this.data.myApplyParams.pageNo;
    pageNo ++;
    _this.setData({
      'myApplyParams.pageNo':pageNo
    });
    _this.loadMyApplyList(true);
  },
  // 我审批的申请单上拉刷新
  refreshMyApprovalList(e){
    var _this = this;
    _this.setData({
      'myApprovalParams.pageNo':0
    });
    _this.loadMyApprovalList(false);
  },
  // 我审批的申请单下拉加载更多数据
  loadMoreMyApprovalList(e){
    var _this = this;
    var pageNo = _this.data.myApprovalParams.pageNo;
    pageNo ++;
    _this.setData({
      'myApprovalParams.pageNo':pageNo
    });
    _this.loadMyApprovalList(true);
  },
  // 抄送我的申请单上拉刷新
  refreshMyCCList(e){
    var _this = this;
    _this.setData({
      'myCCParams.pageNo':0
    });
    _this.loadMyCCList(false);
  },
  // 抄送我的申请单下拉加载更多数据
  loadMoreMyCCList(e){
    var _this = this;
    var pageNo = _this.data.myCCParams.pageNo;
    pageNo ++;
    _this.setData({
      'myCCParams.pageNo':pageNo
    });
    _this.loadMyCCList(true);
  },
  // 跳转申请单详情页面
  bindApplyClick(e){
    var id = e.currentTarget.dataset.id;
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '../applydetail/index?id=' + id + '&type=' + type,
    })
  },
  // 撤销申请单
  bindRevoke(e){
    var _this = this;
    var id = parseInt(e.currentTarget.dataset.id);
    wx.showModal({
      title:'撤销申请单',
      content:'您确定要撤销此申请单吗？',
      success(r){
        if(r.confirm){
            requestClient.revokeApply(id,function(res){
                _this.loadMyApplyList(false);
            })
        }
      }
    })
  },
  // 点击转交申请单，显示用户选择框
  bindReplace(e){
    var _this = this;
    var id = parseInt(e.currentTarget.dataset.id);
    var replace = e.currentTarget.dataset.replace;
    if(replace){
      var _this = this;
      _this.setData({
        showUserDialog:true,
        replaceApplyId:id
      });
    }
  },
  // 重提单据
  bindResubmit(e){
    var _this = this;
    var id = e.currentTarget.dataset.id;
    requestClient.getApplyInfo(id,function(res){
      var apply = res.data.data;
      if(apply){
        wx.setStorageSync('useSealData', apply)
        _this.setData({
          'formData.reason':apply.reason,
          'formData.fileName':apply.fileName,
          'formData.fileNumber':apply.fileNumber,
          'formData.applyCount':apply.applyCount,
          facePhoto:apply.facePhoto,
          stampPhotograph:apply.stampPhotograph,
        });
        // 设置选中的页签
        var e = {detail:{
          index:0
        }}
        // 切换页签
        _this.tabChange(e);
      } else {
        wx.showToast({
          title: '单据不存在！',
          icon:'error'
        })
      }
    })
  },
  // 选择用户
  userCheckboxChange(e){
    var _this = this;
    _this.setData({
      checkUserId: parseInt(e.detail.value)
    });
  },
  // 确认勾选用户
  bindUserCheck(e){
    var _this = this;
    _this.setData({
      showUserDialog:false
    });
    if(_this.data.checkUserId == 0){
      wx.showToast({
        title: '请选择用户！',
        icon:"error",
        mask:true
      })
      return ;
    }
    wx.showModal({
      title:'转交申请单',
      content:'您确定要转交此申请单吗？',
      success(r){
        if(r.confirm){
            requestClient.replaceApply(_this.data.replaceApplyId,_this.data.checkUserId,function(res){
                _this.loadMyApplyList(false);
            })
        }
      }
    })
  },
  bindClosedUser(e){
    this.setData({
      checkUserId:0
    });
  },
  // 处理申请单
  bindHandler(e){
    var _this = this;
    var id = parseInt(e.currentTarget.dataset.id);
    var status = parseInt(e.currentTarget.dataset.status);
    // 同意单据
    if(status == 2){
      // wx.showModal({
      //   title:"处理申请单",
      //   content:'您是否同意此申请单？',
      //   success(r){
      //     if(r.confirm){
      //       var approvalData = {
      //         applyId:id,
      //         userId:_this.data.userId,
      //         approvalResult:status,
      //         approvalComment:"同意"
      //       };
      //       requestClient.approvalApply(approvalData,function(res){
      //          _this.loadMyApprovalList(false);
      //       })
      //     }
      //   }
      // })
      // 输入备注
      _this.setData({
        showAgreeDialog:true,
        agreeApplyId:id,
        agreeComment:'同意'
      });
    } else {
      // 驳回单据
      _this.setData({
        showRejectDialog:true,
        rejectApplyId:id,
        rejectComment:''
      });
    }
  },
  // 输入同意备注
  formAgreeInputChange(e){
    this.setData({
      agreeComment:e.detail.value
    });
  },
  // 确认同意申请单
  bindAgreeApply(e){
    var _this = this;
    _this.setData({
      showAgreeDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var agreeComment = _this.data.agreeComment;
    if(agreeComment == "" || agreeComment.trim() == ""){
      wx.showToast({
        title:"请输入审批意见!",
        icon:"error"
      });
      return;
    }
    var approvalData = {
      applyId:_this.data.agreeApplyId,
      userId:_this.data.userId,
      approvalResult:2,
      approvalComment:agreeComment,
    };
    requestClient.approvalApply(approvalData,function(res){
       _this.loadMyApprovalList(false);
    })
  },
  // 输入驳回原因
  formRejectInputChange(e){
    this.setData({
      rejectComment:e.detail.value
    });
  },
  // 确认驳回申请单
  bindRejectApply(e){
    var _this = this;
    _this.setData({
      showRejectDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var rejectComment = _this.data.rejectComment;
    if(rejectComment == "" || rejectComment.trim() == ""){
      wx.showToast({
        title:"请输入驳回原因!",
        icon:"error"
      });
      return;
    }
    var approvalData = {
      applyId:_this.data.rejectApplyId,
      userId:_this.data.userId,
      approvalResult:3,
      approvalComment:rejectComment
    };
    requestClient.approvalApply(approvalData,function(res){
       _this.loadMyApprovalList(false);
    })
  },
  tabChange(e) {
    var index = e.detail.index;
    var _this = this;
    _this.setData({
      blockId: index,
      'navbarData.title':_this.data.titles[index]
    });
    wx.setNavigationBarTitle({
      title: _this.data.titles[index]
    })
    if(index == 1){
      _this.setData({
        'myApplyParams.userId':_this.data.userId,
        'myApplyParams.approvalStatus':null,
        'myApplyParams.fileType':null,
        'myApplyParams.applyUserId':null,
        'myApplyParams.duration':null,
        'myApplyParams.handlerStatus':null,
        'myApplyParams.keyWords':null,
        'myApplyParams.pageNo':0
      });
      _this.loadMyApplyList(false);
    } else if(index == 2){
      _this.setData({
        'myApprovalParams.userId':_this.data.userId,
        'myApprovalParams.approvalStatus':null,
        'myApprovalParams.fileType':null,
        'myApprovalParams.applyUserId':null,
        'myApprovalParams.duration':null,
        'myApprovalParams.handlerStatus':_this.data.handleStatusNumber,
        'myApprovalParams.keyWords':null,
        'myApprovalParams.pageNo':0
      });
      _this.loadMyApprovalList(false);
    } else if(index == 3){
      _this.setData({
        'myCCParams.userId':_this.data.userId,
        'myCCParams.approvalStatus':null,
        'myCCParams.fileType':null,
        'myCCParams.applyUserId':null,
        'myCCParams.duration':null,
        'myCCParams.handlerStatus':null,
        'myCCParams.keyWords':null,
        'myCCParams.pageNo':0
      });
      _this.loadMyCCList(false);
    }
  }
})